package com.asj.service.command.specific;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.asj.MainActivity;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.JsonObject;

import java.io.File;
import java.io.OutputStream;

/**
 * 动态更换logo图片和名称
 * */
public class SpecificUpdateAppLogoAndNameService {
    public static void updateAppLogoAndName(Context context){
        new Thread(()->{
            Glide.with(context)
                    .load("http://qny.aisheji.team/mdm/app_versions/appLogo.jpg")
                    .into(new CustomTarget<Drawable>() {
                        @Override
                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                            //保存图片
                            File lmLkAppLogo = saveBitmapToFile(context, resource, "lmLk_appLogo");
                            if(lmLkAppLogo != null){
                                //创建新的快捷方式
                                updateShortcutIcon(context,lmLkAppLogo);
                                //加载图片
                                restartLauncher(context);
                            }
                        }
                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {
                            Log.e("GlideLoad", "图片加载失败！");
                        }
                        @Override
                        public void onLoadFailed(@Nullable Drawable errorDrawable) {
                            Log.e("GlideLoad", "图片加载失败！");
                        }
                    });
        }).start();
    }

    private static void updateShortcutIcon(Context context, File imageFile) {
        ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
        if (shortcutManager != null && shortcutManager.isRequestPinShortcutSupported()) {
            ShortcutInfo shortcut = new ShortcutInfo.Builder(context, "shortcut_id")
                    .setShortLabel("新图标")
                    .setLongLabel("这是新的应用图标")
                    .setIcon(Icon.createWithFilePath(imageFile.getAbsolutePath())) // 使用本地文件创建图标
                    .setIntent(new Intent(Intent.ACTION_MAIN, Uri.EMPTY, context, MainActivity.class))
                    .build();
            shortcutManager.requestPinShortcut(shortcut, null);
        }
    }



    public static File saveBitmapToFile(Context context, Drawable drawable, String fileName) {
        try {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            // 对于Android 10及以上版本，使用MediaStore的apply方法
            Uri contentUri;
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else {
                contentUri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
            }

            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
            contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
            contentValues.put(MediaStore.MediaColumns.IS_PENDING, 1);
            Uri uri = context.getContentResolver().insert(contentUri, contentValues);
            if (uri == null) return null;
            try (OutputStream os = context.getContentResolver().openOutputStream(uri)) {
                assert os != null;
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
                // 告诉系统文件准备好了
                contentValues.clear();
                contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
                context.getContentResolver().update(uri, contentValues, null, null);
            } catch (Exception e) {
                e.printStackTrace();
                // 失败时删除uri记录
                context.getContentResolver().delete(uri, null, null);
            }
            // 获取文件路径
            String filePath = getRealPathFromURI(context, uri);
            if (filePath != null) {
                return new File(filePath);
            } else {
                // 如果获取路径失败，删除uri记录
                context.getContentResolver().delete(uri, null, null);
                return null;
            }
        } catch (Exception e) {
            Log.e("保存文件失败！", "保存文件失败", e);
        }
        return null;
    }

    // 辅助方法，用于从Uri获取实际文件路径
    private static String getRealPathFromURI(Context context, Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        assert cursor != null;
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String path = cursor.getString(column_index);
        cursor.close();
        return path;
    }

    public static void restartLauncher(Context context) {
        Intent intent = new Intent("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.HOME");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}
